package com.wlyuan.open.scanner.domain.message;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Slf4j
public class MessageListenerParse {

    /**
     * 解析消息
     *
     * @param message
     * @return
     */
    public static MessageData parse(String message) {
        var changeEnvelope = JSON.parseObject(message, MessageEnvelope.class);
        return Optional.ofNullable(changeEnvelope)
                .filter(read -> !OperationTypeEnum.isRead(read.getOp()))
                .map(MessageListenerParse::parseEnvelope).orElse(null);
    }

    /**
     * 数据信息源解析
     *
     * @param envelope
     * @return
     */
    private static MessageData parseEnvelope(MessageEnvelope envelope) {
        //表名解析
        var tableName = MessageTableParse.getTableName(envelope.getSource());
        if (StringUtils.isBlank(tableName)) {
            logger.error("表名解析失败");
            return null;
        }
        //数据解析
        var messageData = MessageDataParse.parse(tableName, envelope);
        if (!Optional.ofNullable(messageData).isPresent()) {
            logger.error("数据解析失败");
            return null;
        }
        // id列解析构建
        var id = BuildAutoIdColumn.build(tableName, messageData.getData());
        if (Objects.isNull(id)) {
            logger.error("{}未获取到主键id值", tableName);
            return null;
        }
        messageData.setId(id);
        return messageData;
    }

}
